
import { FormControl } from "@angular/forms/src/model";

export default class CustomValidators {
  /**
   * sample from http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
   */
  static validateEmail(c: FormControl) {
    // tslint:disable-next-line:max-line-length
    const EMAIL_REGEXP = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;

    return EMAIL_REGEXP.test(c.value) ? null : {
      validateEmail: {
        valid: false
      }
    };
  }

  static validatePhone(c: FormControl) {
    const EMAIL_REGEXP = /^1[0-9]{10}$/; // /^1(3|4|5|7|8)\d{9}$/;

    return EMAIL_REGEXP.test(c.value) ? null : {
      validatePhone: {
        valid: false
      }
    };
  }

  static validatePassword(c: FormControl) {
    const Upper_REGEXP =  /[A-Z]/;
    const lower_REGEXP =  /[a-z]/;
    const number_REGEXP =  /\d/;
    return Upper_REGEXP.test(c.value) && lower_REGEXP.test(c.value) && number_REGEXP.test(c.value) ? null :{validatePassword: {
        valid: false
      }
    };
  }

  static passwordMatchValidator(attr: string) {
    return function (g: FormControl) {
      // self value (e.g. retype password)
      const v = g.value;
      // control value (e.g. password)
      const e = g.root.get(attr);
      // value not equal
      // tslint:disable-next-line:curly
      if (e && v !== e.value) return {
        validateEqual: {
          valid: false
        }
      }
      return null;
    }
  }


  static validateIdCard(c: FormControl) {
    if ( !c.value) {
      return null ;
    }

    // tslint:disable-next-line:max-line-length
    const IdCard_RegExp = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/;
    return IdCard_RegExp.test(c.value) ? null : {
      validateIdCard: {
        valid: false
      }
    };
  }

  static validUserName( c: FormControl ) {
    if (!c.value) {
      return {
        validUserName: {
          valid: false,
          errorMsg: "姓名不允许为空"
        }
      }
    }

    const userName_RegExp = /^[\u4e00-\u9fa5·a-zA-Z]+$/;
    // /^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$/;    // /[\u4E00-\u9FA5]{2,5}(?:·[\u4E00-\u9FA5]{2,5})*/;
    return (userName_RegExp.test(c.value.trim()) ? null : {
      validUserName: {
        valid: false,
        errorMsg: "请数正确的中英文姓名"
      }
    })
  }
}
